package com.yaowk.platform.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.JMap;
import com.yaowk.authc.model.OnlineCount;
import com.yaowk.authc.model.User;
import com.yaowk.common.kit.ResultKit;
import com.yaowk.common.validator.RequiredIdValidator;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 数据统计
 *
 * @authc yaowk
 * 2017/4/29
 */
public class CountController extends Controller {

    /**
     * 查询在线人数和用户总数
     *
     * @param id|平台id|Integer|必填
     * @title 查询在线人数和用户总数
     */
    @Before(RequiredIdValidator.class)
    @RequiresPermissions("platform:read")
    public void number() {
        Integer id = getParaToInt("id");
        Integer online = (Integer) getSession().getServletContext().getAttribute(id.toString());
        Long totalUser = User.dao.count(id);
        JMap jMap = JMap.create("online", online).set("totalUser", totalUser);
        renderJson(ResultKit.success(jMap));
    }

    /**
     * 获取历史数据
     *
     * @param id|平台id|Integer|必填
     * @param beginTime|开始时间|Long|否
     * @param endTime|结束时间|Long|否
     * @title 获取历史数据
     */
    @Before(RequiredIdValidator.class)
    @RequiresPermissions("platform:read")
    public void list() {
        Integer id = getParaToInt("id");
        Date beginTime = getParaToDate("beginTime");
        Date endTime = getParaToDate("endTime");
        List<OnlineCount> onlineCountList = OnlineCount.dao.findByDate(id, beginTime, endTime);
        List<Map<String, Object>> list = new ArrayList<>();
        for (OnlineCount onlineCount : onlineCountList) {
            list.add(JMap.create().set("time", onlineCount.getTime().getTime()).set("value", onlineCount.getNumber()));
        }
        renderJson(ResultKit.success(list));
    }
}
